package com.policyCloud.policyGateway.properties;


import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;


@Data
@Configuration
public class PermitAllUrlProperties {

    /** 不管理的地址 **/
    private static String strFilter ;
    @Value("${strFilter}")
    public void setStrFilter(String strFilter) {
        this.strFilter = strFilter;
    }

    private static List<Pattern> permitallUrlPattern;


    @Bean
    public void getPermitallPatterns() {
        String[] strings = StringUtils.split(strFilter, ",");
        List<String> permitall = new ArrayList<>();
        for (int i = 0; i < strings.length; i++) {
            permitall.add(strings[i]);
        }
        if (permitall != null && permitall.size() > 0) {
            this.permitallUrlPattern = new ArrayList();
//            Iterator<url> iterator = permitall.iterator();
//            while (iterator.hasNext()) {
//                String currentUrl = iterator.next().getPattern().replaceAll("\\*\\*", "(.*?)");
//                Pattern currentPattern = Pattern.compile(currentUrl, Pattern.CASE_INSENSITIVE);
//                permitallUrlPattern.add(currentPattern);
//            }
            permitall.forEach(x ->{
                String currentUrl = x.replaceAll("\\*\\*", "(.*?)");
                Pattern currentPattern = Pattern.compile(currentUrl, Pattern.CASE_INSENSITIVE);
                permitallUrlPattern.add(currentPattern);
            });

        }
    }

    public boolean isPermitAllUrl(String url) {
        for (Pattern pattern : permitallUrlPattern) {
            if (pattern.matcher(url).find()) {
                return true;
            }
        }
        return false;
    }
}

